package org.jgs1904.tieba.service.impl;

import org.jgs1904.tieba.entity.User;
import org.jgs1904.tieba.entity.UserMail;
import org.jgs1904.tieba.enums.UserMailStatusEnum;
import org.jgs1904.tieba.repository.UserMailRepository;
import org.jgs1904.tieba.repository.UserRepository;
import org.jgs1904.tieba.service.UserMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Optional;

/**
 * @author junki
 * @date 2020/5/12 14:40
 */
@Service
@Transactional
public class UserMailServiceImpl implements UserMailService {

    @Autowired
    private UserMailRepository userMailRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserMail save(UserMail UserMail) {
        List<UserMail> result = userMailRepository.findByUserIdAndStatus(UserMail.getUserId(), UserMailStatusEnum.UNUSED);
        if (CollectionUtils.isEmpty(result)) {
            result.forEach(userMail -> userMail.setStatus(UserMailStatusEnum.OUTTIME));
            userMailRepository.saveAll(result);
        }
        return userMailRepository.save(UserMail);
    }

    @Override
    public UserMail activeByToken(String token) {
        UserMail result = userMailRepository.findByTokenAndStatus(token, UserMailStatusEnum.UNUSED);
        if (result != null) {
            Optional<User> userOptional = userRepository.findById(result.getUserId());
            if (userOptional.isPresent()) {
                User user = userOptional.get();
                user.setActive((byte)1);
                userRepository.save(user);

                result.setStatus(UserMailStatusEnum.USED);
                result = userMailRepository.save(result);
            }
        }
        return result;
    }

    @Override
    public UserMail changeUserPwdByToken(String password, String token) {
        UserMail result = userMailRepository.findByTokenAndStatus(token, UserMailStatusEnum.UNUSED);
        if (result != null) {
            Optional<User> userOptional = userRepository.findById(result.getUserId());
            if (userOptional.isPresent()) {
                User user = userOptional.get();
                user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
                userRepository.save(user);

                result.setStatus(UserMailStatusEnum.USED);
                result = userMailRepository.save(result);
            }
        }
        return result;
    }


}
